<template>
  <div class="p-6 space-y-6">
    <div class="text-center">
      <h2 class="text-xl font-bold text-gray-900 mb-2">网络连接测试</h2>
      <p class="text-gray-600">诊断网络连接问题</p>
    </div>

    <div class="space-y-4">
      <button
        @click="testBackendConnection"
        :disabled="testing"
        class="w-full btn-primary disabled:opacity-50"
      >
        {{ testing ? '测试中...' : '测试后端连接' }}
      </button>

      <button
        @click="testAuthAPI"
        :disabled="testing"
        class="w-full btn-secondary disabled:opacity-50"
      >
        测试认证API
      </button>

      <button
        @click="testCORS"
        :disabled="testing"
        class="w-full btn-secondary disabled:opacity-50"
      >
        测试CORS配置
      </button>

      <button
        @click="testMicrophonePermission"
        :disabled="testing"
        class="w-full btn-secondary disabled:opacity-50"
      >
        测试麦克风权限
      </button>
    </div>

    <div v-if="testResults.length > 0" class="space-y-4">
      <h3 class="text-lg font-medium text-gray-900">测试结果</h3>
      <div
        v-for="(result, index) in testResults"
        :key="index"
        :class="[
          'p-4 rounded-lg border',
          result.success ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'
        ]"
      >
        <div class="flex justify-between items-start">
          <div>
            <div class="font-medium" :class="result.success ? 'text-green-800' : 'text-red-800'">
              {{ result.title }}
            </div>
            <div class="text-sm mt-1" :class="result.success ? 'text-green-600' : 'text-red-600'">
              {{ result.message }}
            </div>
          </div>
          <div class="text-2xl">
            {{ result.success ? '✅' : '❌' }}
          </div>
        </div>
        <div v-if="result.details" class="mt-2 text-xs text-gray-600">
          <pre class="whitespace-pre-wrap">{{ result.details }}</pre>
        </div>
      </div>
    </div>

    <div class="bg-gray-50 p-4 rounded-lg">
      <h3 class="text-sm font-medium text-gray-700 mb-2">系统信息</h3>
      <div class="text-xs text-gray-600 space-y-1">
        <div>用户代理: {{ userAgent }}</div>
        <div>当前URL: {{ currentUrl }}</div>
        <div>API地址: {{ apiUrl }}</div>
        <div>网络状态: {{ networkStatus }}</div>
        <div>在线状态: {{ navigator.onLine ? '在线' : '离线' }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { config } from '@/utils/config';

const testing = ref(false);
const testResults = ref<Array<{
  title: string;
  message: string;
  success: boolean;
  details?: string;
}>>([]);

const userAgent = ref('');
const currentUrl = ref('');
const apiUrl = ref(config.api.baseUrl);
const networkStatus = ref('');

onMounted(() => {
  userAgent.value = navigator.userAgent;
  currentUrl.value = window.location.href;
  checkNetworkStatus();
});

const checkNetworkStatus = () => {
  if (navigator.onLine) {
    networkStatus.value = '网络连接正常';
  } else {
    networkStatus.value = '网络连接异常';
  }
};

const addTestResult = (title: string, success: boolean, message: string, details?: string) => {
  testResults.value.unshift({
    title,
    success,
    message,
    details
  });
};

const testBackendConnection = async () => {
  testing.value = true;
  
  try {
    const response = await fetch(`${config.api.baseUrl}/api/auth/test`, {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      const data = await response.json();
      addTestResult(
        '后端连接测试',
        true,
        '连接成功',
        JSON.stringify(data, null, 2)
      );
    } else {
      addTestResult(
        '后端连接测试',
        false,
        `服务器返回错误状态码: ${response.status}`,
        `状态: ${response.status} ${response.statusText}`
      );
    }
  } catch (error: any) {
    console.error('后端连接测试失败:', error);
    addTestResult(
      '后端连接测试',
      false,
      '连接失败',
      `错误: ${error.message}\n类型: ${error.name}`
    );
  } finally {
    testing.value = false;
  }
};

const testAuthAPI = async () => {
  testing.value = true;
  
  try {
    const response = await fetch(`${config.api.baseUrl}/api/auth/login`, {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        userName: 'testuser',
        password: 'testpass'
      })
    });
    
    const data = await response.json();
    
    if (response.status === 401) {
      addTestResult(
        '认证API测试',
        true,
        'API端点正常，认证失败是预期的（测试用户不存在）',
        JSON.stringify(data, null, 2)
      );
    } else if (response.ok) {
      addTestResult(
        '认证API测试',
        true,
        'API端点正常，认证成功',
        JSON.stringify(data, null, 2)
      );
    } else {
      addTestResult(
        '认证API测试',
        false,
        `API端点异常，状态码: ${response.status}`,
        JSON.stringify(data, null, 2)
      );
    }
  } catch (error: any) {
    console.error('认证API测试失败:', error);
    addTestResult(
      '认证API测试',
      false,
      'API调用失败',
      `错误: ${error.message}\n类型: ${error.name}`
    );
  } finally {
    testing.value = false;
  }
};

const testCORS = async () => {
  testing.value = true;
  
  try {
    // 测试预检请求
    const response = await fetch(`${config.api.baseUrl}/api/auth/test`, {
      method: 'OPTIONS',
      mode: 'cors',
      headers: {
        'Origin': window.location.origin,
        'Access-Control-Request-Method': 'GET',
        'Access-Control-Request-Headers': 'Content-Type'
      }
    });
    
    const corsHeaders = {
      'Access-Control-Allow-Origin': response.headers.get('Access-Control-Allow-Origin'),
      'Access-Control-Allow-Methods': response.headers.get('Access-Control-Allow-Methods'),
      'Access-Control-Allow-Headers': response.headers.get('Access-Control-Allow-Headers'),
      'Access-Control-Allow-Credentials': response.headers.get('Access-Control-Allow-Credentials')
    };
    
    addTestResult(
      'CORS配置测试',
      true,
      'CORS预检请求成功',
      JSON.stringify(corsHeaders, null, 2)
    );
  } catch (error: any) {
    console.error('CORS测试失败:', error);
    addTestResult(
      'CORS配置测试',
      false,
      'CORS预检请求失败',
      `错误: ${error.message}\n类型: ${error.name}`
    );
  } finally {
    testing.value = false;
  }
};

// 测试麦克风权限
const testMicrophonePermission = async () => {
  console.log('开始测试麦克风权限...');
  
  try {
    // 检查API支持
    const hasMediaDevices = !!navigator.mediaDevices;
    const hasGetUserMedia = !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
    
    console.log('API支持检查:', {
      mediaDevices: hasMediaDevices,
      getUserMedia: hasGetUserMedia
    });
    
    if (!hasMediaDevices && !hasGetUserMedia) {
      testResults.value.microphone = {
        status: 'error',
        message: '浏览器不支持麦克风API'
      };
      return;
    }
    
    // 尝试获取权限
    let stream: MediaStream | null = null;
    
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    } else {
      // 使用旧版API
      stream = await new Promise<MediaStream>((resolve, reject) => {
        const getUserMedia = navigator.getUserMedia || 
                           navigator.webkitGetUserMedia || 
                           navigator.mozGetUserMedia || 
                           navigator.msGetUserMedia;
        
        getUserMedia.call(navigator, { audio: true }, resolve, reject);
      });
    }
    
    // 检查音频轨道
    const audioTracks = stream.getAudioTracks();
    if (audioTracks.length > 0) {
      const track = audioTracks[0];
      console.log('麦克风信息:', {
        label: track.label,
        enabled: track.enabled,
        muted: track.muted,
        readyState: track.readyState
      });
      
      testResults.value.microphone = {
        status: 'success',
        message: `麦克风权限获取成功\n设备: ${track.label || '未知设备'}`
      };
    } else {
      testResults.value.microphone = {
        status: 'warning',
        message: '获取到音频流但未检测到音频轨道'
      };
    }
    
    // 立即停止录音
    stream.getTracks().forEach(track => track.stop());
    
  } catch (error: any) {
    console.error('麦克风权限测试失败:', error);
    
    let message = '麦克风权限测试失败';
    if (error.name === 'NotAllowedError') {
      message = '麦克风权限被拒绝\n请检查浏览器权限设置';
    } else if (error.name === 'NotFoundError') {
      message = '未找到麦克风设备';
    } else if (error.name === 'NotSupportedError') {
      message = '浏览器不支持音频录制';
    } else if (error.name === 'SecurityError') {
      message = '安全错误\n请在HTTPS环境下测试';
    }
    
    testResults.value.microphone = {
      status: 'error',
      message: message
    };
  }
};
</script> 